package com.ruoyi.web.controller.tool;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.annotation.AreaSharding;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.service.GuidRedisService;

import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * swagger 用户测试方法
 *
 * @author ruoyi
 */
@Api("用户信息管理")
@RestController
@RequestMapping("/test/user")
@Slf4j
public class TestController extends BaseController {

    @Autowired
    private GuidRedisService guidRedisService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private final static Map<Integer, UserEntity> users = new LinkedHashMap<Integer, UserEntity>();

    {
        users.put(1, new UserEntity(1, "admin", "admin123", "15888888888"));
        users.put(2, new UserEntity(2, "ry", "admin123", "15666666666"));
    }

    @ApiOperation("获取用户列表")
    @GetMapping("/list")
    public AjaxResult userList() {
        List<UserEntity> userList = new ArrayList<UserEntity>(users.values());
        return AjaxResult.success(userList);
    }

    @ApiOperation("获取用户详细")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path")
    @GetMapping("/{userId}")
    public AjaxResult getUser(@PathVariable Integer userId) {
        if (!users.isEmpty() && users.containsKey(userId)) {
            return AjaxResult.success(users.get(userId));
        } else {
            return AjaxResult.error("用户不存在");
        }
    }

    @ApiOperation("新增用户")
    @ApiImplicitParam(name = "userEntity", value = "新增用户信息", dataType = "UserEntity")
    @PostMapping("/save")
    public AjaxResult save(UserEntity user) {
        if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) {
            return AjaxResult.error("用户ID不能为空");
        }
        return AjaxResult.success(users.put(user.getUserId(), user));
    }

    @ApiOperation("更新用户")
    @ApiImplicitParam(name = "userEntity", value = "新增用户信息", dataType = "UserEntity")
    @PutMapping("/update")
    public AjaxResult update(UserEntity user) {
        if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) {
            return AjaxResult.error("用户ID不能为空");
        }
        if (users.isEmpty() || !users.containsKey(user.getUserId())) {
            return AjaxResult.error("用户不存在");
        }
        users.remove(user.getUserId());
        return AjaxResult.success(users.put(user.getUserId(), user));
    }

    @ApiOperation("删除用户信息")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path")
    @DeleteMapping("/{userId}")
    public AjaxResult delete(@PathVariable Integer userId) {
        if (!users.isEmpty() && users.containsKey(userId)) {
            users.remove(userId);
            return AjaxResult.success();
        } else {
            return AjaxResult.error("用户不存在");
        }
    }

    @ApiOperation("测试数据")
    @GetMapping("/testId")
    public AjaxResult testId() {
        Set<Long> id = new HashSet<>();
        for (int i = 0; i < 10000000; i++) {
            Long work = guidRedisService.nextId();
            System.out.println(work);
            id.add(work);
        }
        System.out.println(id.size());
        return AjaxResult.success();


    }

    @ApiOperation("测试数据")
    @GetMapping("/testZookId")
    public AjaxResult testZookId() {
        Set<Long> id = new HashSet<>();
        for (int i = 0; i < 10000; i++) {
           // Long work = guidService.nextId();
            //System.out.println(work);
            //id.add(work);
        }
        System.out.println(id.size());
        return AjaxResult.success();


    }

    @ApiOperation("测试数据")
    @GetMapping("/testIdM")
    @AreaSharding
    public AjaxResult testProductIdByMoreThread() throws InterruptedException {
//        List<Thread> tlist = new ArrayList<>();
//        Set<Long> setAll = new HashSet<>();
//        CountDownLatch cdLatch = new CountDownLatch(10);
//        long start = System.currentTimeMillis();
//        int n=100000;
//
//        List<Future<Long>> futureList=new ArrayList<>();
//
//        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("redis-work-id-%d").build();
//        ExecutorService exec = Executors.newFixedThreadPool(10,namedThreadFactory);
//        //FutureTask<Long> futureTask = new FutureTask<>(new Calculate(countDownLatch));
//        // 执行任务
//        //futureTask.run();
//        // 添加任务到队列中，方便后续进行数据输出
//        //futureList.add(futureTask);
//
//        for(int i=0;i<10;i++){
////            Thread temp =new Thread(new Runnable() {
////                @Override
////                public void run() {
////                    Set<Long> setId = new HashSet<>();
////
////                    for(int j=0;j<n;j++){
////                        Long id=guidRedisService.nextId();
////                        setId.add(id);
////                        log.info("{}生产了id:{}",Thread.currentThread().getName(),id);
////                    }
////                    synchronized (setAll){
////                        setAll.addAll(setId);
////                        log.info("{}生产了{}个id,并成功加入到setAll中.",Thread.currentThread().getName(),n);
////                    }
////                    cdLatch.countDown();
////                }
////            },"snowflake"+i);
////            tlist.add(temp);
//            futureList.add(exec.submit(new IdTestCallable(guidRedisService,n)));
//
//
//        }
//        for (Future<Long> fs : futureList) {
//            if (fs.isDone()) {
//                try {
//                   setAll.addAll(Collections.singleton(fs.get()));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            } else {
//                System.out.println("MyCallableTask任务未完成！");
//            }
//        }
//        exec.shutdown();
//
//        cdLatch.await();
//
//        long end1 = System.currentTimeMillis() - start;
//
//        log.info("共耗时:{}毫秒,预期应该生产{}个id, 实际合并总计生成ID个数:{}",end1,10*n,setAll.size());


        return AjaxResult.success(guidRedisService.nextId());


    }


    @ApiOperation("测试数据")
    @GetMapping("/testArea")
    @AreaSharding
    public List<Long> testArea() throws InterruptedException {
        List<Long> result=new ArrayList<>();
        result.add(guidRedisService.nextId());
        return result;
    }

    @ApiOperation("测试数据")
    @PostMapping("/testAreaCode")
    @AreaSharding
    public List<Long> testAreaCode(@RequestBody Map<String,String> area) throws InterruptedException {
        System.out.println(area);
        List<Long> result=new ArrayList<>();
        result.add(guidRedisService.nextId());
        return result;
    }



    @ApiOperation("测试数据")
    @GetMapping("/getWorkResult")
    public AjaxResult getWorkIdResult() {
        Map<String, Long> map = new HashMap<>();
        logger.error("GuidRedisService.create()" + "\n"+
                        "set Size:{}" + "\n"+
                        "list Size:{}"
                ,redisTemplate.boundSetOps("GUID_WORK_SET").size()
                ,redisTemplate.boundListOps("GUID_WORK_LIST").size());
        map.put("list", redisTemplate.boundListOps("GUID_WORK_LIST").size());
        map.put("set", redisTemplate.boundSetOps("GUID_WORK_SET").size());


        Set<Long> setArray = new HashSet<>();
        Long id = 0L;
        do {

            id = (Long) redisTemplate.boundListOps("GUID_WORK_LIST").rightPop();
            if(id==null){
                continue;
            }
            setArray.add((Long) id);
            logger.debug("存储"+id);
        } while (id !=null);
        //List<Object> range = redisTemplate.boundListOps("GUID_WORK_LIST").range(0, redisTemplate.boundListOps("GUID_WORK_LIST").size());
//        range.stream().forEach(id->{
//            setArray.add((Long) id);
//        });

        map.put("set&list", (long) setArray.size());
        logger.error("数据测试结果：{}", JSON.toJSONString(map));
        return AjaxResult.success(map);
    }


}

@ApiModel("用户实体")
class UserEntity {
    @ApiModelProperty("用户ID")
    private Integer userId;

    @ApiModelProperty("用户名称")
    private String username;

    @ApiModelProperty("用户密码")
    private String password;

    @ApiModelProperty("用户手机")
    private String mobile;

    public UserEntity() {

    }

    public UserEntity(Integer userId, String username, String password, String mobile) {
        this.userId = userId;
        this.username = username;
        this.password = password;
        this.mobile = mobile;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}

class AreaCode{
    private String bdsId;
    private String bdsIds;

    public String getBdsId() {
        return bdsId;
    }

    public void setBdsId(String bdsId) {
        this.bdsId = bdsId;
    }

    public String getBdsIds() {
        return bdsIds;
    }

    public void setBdsIds(String bdsIds) {
        this.bdsIds = bdsIds;
    }

    public AreaCode() {
    }

    public AreaCode(String bdsId, String bdsIds) {
        this.bdsId = bdsId;
        this.bdsIds = bdsIds;
    }
}
